﻿//======================================================================
//
//        Copyright (C) 2015   
//        All rights reserved
//
//        filename : NotSaleCard
//        description : 未售问题卡回收
//        created by XXX at  20160115
//
//======================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CardLogistics.Web.Components;
using System.Data;
using System.Text;
using System.IO;
using System.Data.OleDb;

namespace CardLogistics.Web.MainPage.CardRecovery.NotSaleCard
{
    public partial class AddEdit : BasePage
    {
        private static readonly CardLogistics.DAL.CardRecovery.NotSaleCardData DAL = new DAL.CardRecovery.NotSaleCardData();
        private static readonly CardLogistics.DAL.CardRecovery.NotSaleCard_DetailData DDAL = new CardLogistics.DAL.CardRecovery.NotSaleCard_DetailData();
        string recoveryId = "";//未售问题卡Id
        /// <summary>
        /// 增加的行
        /// </summary>
        protected StringBuilder AddTr = new StringBuilder();
        public static string TitleName;
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                RECOVERYDATE.Value = DateTime.Now.ToString("yyyy-MM-dd");//回收日期
                BindGroup();
                InitControl();

            }
        }

        #region 编辑时绑定值
        /// <summary>
        /// 编辑时绑定值
        /// </summary>
        public void InitControl()
        {
            TitleName = GetStatusInfo(0, "未售问题卡回收");
            if (IsEdit)
            {
                string _key = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(_key))
                {
                    CardLogistics.Model.CardRecovery.NotSaleCard pData = DAL.GetModel(_key);
                    SetWebControls(this.Page, pData);
                    DataTable dt = DDAL.GetInfoByRecoveryId(pData.ID);
                    //dt.DefaultView.Sort = "StartCardNo ASC,EndCardNo ASC";//按开始卡号,结束卡号排序
                    DataView dv = dt.DefaultView;
                    dv.Sort = "StartCardNo ASC,EndCardNo ASC";//按开始卡号,结束卡号排序
                    dt = dv.ToTable();
                    string detId = "";
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            detId += dr["StartCardNo"].ToString() + "|" + dr["EndCardNo"].ToString() + "|" + dr["CardAmount"].ToString() + ";";
                        }
                        AddRows(dt);//动态添加行
                        hf_detailId.Value = detId.TrimEnd(';');
                    }
                    RETURNPOINT.SelectedValue = pData.RETURNPOINT;
                    btn_Add.Visible = btn_Submit.Visible = false;
                    if (pData.IsSubmit == 0 || pData.IsSubmit == 3)//状态为 0(未提交) 或 3(驳回)时才可以进行编辑操作
                    {
                        btn_Add.Visible = btn_Submit.Visible = true;
                    }
                    TitleName = GetStatusInfo(int.Parse(pData.IsSubmit.ToString()), "未售问题卡回收");
                }
            }
            else
            {
                RECOVERYNO.Value = GetBillNumber("未售问题卡回收");
            }

        }
        #endregion

        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(0);
                ShowMegByResult(result, 0);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        /// <summary>
        /// 保存并提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(1);
                ShowMegByResult(result, 1);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }

        #region 提示信息
        /// <summary>
        /// 提示信息
        /// </summary>
        /// <param name="result"></param>
        private void ShowMegByResult(string result, int issubmit)
        {
            if (result.Split(',')[0] == "ok")
            {
                if (issubmit == 1)
                {
                    InsertAppInfo(12, result.Split(',')[1]); // 12未售问题卡回收
                    InsertLog("保存并提交未售问题卡回收信息,回收单号:" + RECOVERYNO.Value);
                }
                else
                    InsertLog("保存未售问题卡回收信息,回收单号:" + RECOVERYNO.Value);
                ReturnListInfo();
            }
            else
            {
                ShowMessageBox("操作失败请重新操作！" + result.Split(',')[1]);
            }
        }
        #endregion

        /// <summary>
        /// 未售问题卡回收信息
        /// </summary>
        /// <param name="issubmit">是否提交</param>
        /// <returns></returns>
        private string EncapsulationModel(int issubmit)
        {
            string result = string.Empty;
            CardLogistics.Model.CardRecovery.NotSaleCard model = new Model.CardRecovery.NotSaleCard();
            model = GetWebControls<CardLogistics.Model.CardRecovery.NotSaleCard>(this.Page);
            model.LASTUPDATEUSER = LoggedUser.ID;
            model.LASTUPDATEDATE = DateTime.Now;
            model.RETURNPOINT = RETURNPOINT.SelectedValue.ToString();
            model.IsSubmit = issubmit;
            string FileValue = hf_detailId.Value; //未售问题卡明细字段
            if (IsEdit)
            {
                model.ID = Request.QueryString["id"];
                result = DAL.Update(model, FileValue);
            }
            else
            {
                result = DAL.Add(model, FileValue);
                if (result.Split(',')[0] == "ok")
                {
                    ChgBillNumber("未售问题卡回收");
                }
            }
            return result;
        }

        #region 绑定机构/网点树列表
        /// <summary>
        /// 绑定根节点
        /// </summary>
        void BindGroup()
        {
            DataTable dt = new DAL.Basic.Basic_SalesInfoData().GetList(" ISDELETE=0 ", "*");//获取所有节点
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    if (row["PARENTID"].ToString().Trim() == "0")//绑定根节点
                    {
                        this.RETURNPOINT.Items.Insert(RETURNPOINT.Items.Count, new ListItem(row["SALESNAME"].ToString(), row["Id"].ToString()));
                        this.BindDropChildItem(this.RETURNPOINT, dt, row["Id"].ToString(), 1);
                    }
                }
            }
        }
        /// <summary>
        /// 绑定子节点
        /// </summary>
        /// <param name="d"></param>
        /// <param name="dt"></param>
        /// <param name="id"></param>
        /// <param name="length"></param>
        void BindDropChildItem(DropDownList d, DataTable dt, string id, int length)
        {
            DataRow[] rows = dt.Select("PARENTID='" + id + "'", "Id DESC");//取出id子节点进行绑定
            for (int i = 0; i < rows.Length; i++)
            {
                this.RETURNPOINT.Items.Insert(RETURNPOINT.Items.Count, new ListItem(this.SpaceLength(length) + rows[i]["SALESNAME"].ToString(), rows[i]["Id"].ToString()));
                this.BindDropChildItem(d, dt, rows[i]["Id"].ToString(), length + 1);//空白数目加1
            }
        }
        /// <summary>
        /// 子节点前面的空白数
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        string SpaceLength(int i)
        {
            string space = "┊";
            for (int j = 0; j < i; j++)
            {
                space += "┈┈";//注意这里的空白是智能abc输入法状态下的v11字符；┊┈┈
            }
            return space;
        }
        #endregion

        #region 卡片验收入库导入
        /// <summary>
        /// 卡片验收入库导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //static object basePath = "~/MainPage/File/NotSaleUpFile/"; //读取Excel的路径
        protected void btnImport_Click(object sender, EventArgs e)
        {
            string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//获得文件的扩展名
            if (IsXls != ".xls" && IsXls != ".xlsx")
            {
                ShowMessageBox("只可以选择Excel文件");
                return;
            }
            HttpPostedFile file = this.FileUpload1.PostedFile;

            string filename = FileUpload1.FileName;//获取Execle文件名
            string filePath = Server.MapPath("~/MainPage/File/NotSaleUpFile/" + FileUpload1.FileName);
            file.SaveAs(filePath);
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8"));
            try
            {
                //第一种方法：传统方法，采用OleDB读取EXCEL文件 
                //优点：写法简单，缺点：服务器必须安有此组件才能用，不推荐使用

                //DataSet ds = GetDataFromExcel(filePath, filename);  //调用自定义方法
                //DataTable dt = ds.Tables[0];

                //第二种方法：用第三方组件：NPOI组件,推荐使用此方法
               // DataTable dt = ReadExcel(basePath, filename);
                DataTable dt = ExcelHelper.GetDataTable(filePath);

                //循环移除DataTable中的空行
                List<DataRow> removelist = new List<DataRow>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    bool rowIsNull = true; //标记是否有空行
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
                        {
                            rowIsNull = false;
                        }
                    }
                    if (rowIsNull)
                    {
                        removelist.Add(dt.Rows[i]);
                    }
                }
                for (int i = 0; i < removelist.Count; i++)
                {
                    dt.Rows.Remove(removelist[i]);
                }
                string detId = "";
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        detId += dr["开始卡号"].ToString() + "|" + dr["结束卡号"].ToString() + "|" + dr["数量"].ToString() + ";";
                    }
                    AddRows(dt);//动态添加行
                    hf_detailId.Value = detId.TrimEnd(';');
                }
            }
            catch
            { }
            finally
            {
                fs.Flush(); //释放流
                fs.Close();//关闭流
            }
        }
        #endregion

        #region 模板下载
        /// <summary>
        /// 模板下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDownLoad_Click(object sender, EventArgs e)
        {
            string excelFile = Server.MapPath("~/MainPage/File/DownLoad/未售问题卡导入模板.xls");
            DownLoad(excelFile, "未售问题卡导入模板.xls");
        }
        #endregion

        #region
        /// <summary>
        /// 动态添加行
        /// </summary>
        /// <param name="dt"></param>
        private void AddRows(DataTable dt)
        {
            //动态创建行
            for (int i = 11; i <= dt.Rows.Count; i++)
            {
                AddTr.Append("<tr><td align='center' width='30px'>" + i + "</td>");
                AddTr.Append("<td width='130px'><input name='StartCardNo' type='text' class='dfinput' onkeydown='onlyNum();' maxlength='8'/> </td>");
                AddTr.Append("<td width='130px'><input name='EndCardNo' type='text' class='dfinput' onkeydown='onlyNum();' maxlength='8'/></td>");
                AddTr.Append("<td width='130px'><input name='CardAmount' type='text' class='dfinput' /></td>");
                AddTr.Append("<td>&nbsp;</td></tr>");
            }
        }
        #endregion

    }
}